package com.lanou.pro;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author zyj
 * @date 2022年06月11日 17:22
 */
public class Recevice {
    public static void main(String[] args) {
        //DatagramSocket 指定端口号
        try {
            DatagramSocket socket = new DatagramSocket(80);
            //创建数据包
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            InetAddress address = packet.getAddress();//获取发送端的IP地址
            byte[] bytes = packet.getData();//获取发送端发送的数据
            int length = packet.getLength();//获取发送的数据的长度
            int port = packet.getPort();//获取发送端的端口号
            System.out.println(new String(bytes, 0, length) + "，这个数据来至于" + address + ":" + port);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
